package com.promise.jokerdream.work.signin.newact

import com.promise.jokerdream.manager.ExecutionHistoryManager
import com.promise.jokerdream.repository.GameApi
import com.promise.jokerdream.repository.foldWithApiException
import com.promise.jokerdream.utils.AppContext
import com.promise.jokerdream.work.BaseWork
import com.promise.jokerdream.work.WorkResult

// 幸运转盘工作
class LuckyWheelWork(override val uin: String): BaseWork(uin) {

    override val name: String
        get() = "幸运转盘"

    override val priority: Int
        get() = 8

    override val isActWork: Boolean
        get() = true
    
    private val gameApi = GameApi.getInstance()
    private val historyManager by lazy { ExecutionHistoryManager.getInstance(AppContext.get()) }
    
    override suspend fun executeWork(): WorkResult {
        return try {
            // 查询幸运转盘信息
            val queryResult = gameApi.queryLuckyWheel()
            queryResult.foldWithApiException(
                onSuccess = { response ->
                    val leftTimes = response.leftTimes

                    // 根据剩余次数进行转动
                    for (i in 1..leftTimes) {
                        val spinResult = gameApi.rollLuckyWheel()
                        spinResult.foldWithApiException(
                            onSuccess = { spinResponse ->
                                historyManager.addHistory(name, spinResponse.getDescription())
                            },
                            onFailure = { code, msg ->
                                historyManager.addHistory(name, msg)
                            }
                        )
                    }
                    
                    WorkResult.Success
                },
                onFailure = { code, msg ->
                    historyManager.addHistory(name, msg)
                    WorkResult.Failure(Exception(msg), msg)
                }
            )
        } catch (e: Exception) {
            historyManager.addHistory(name, e.message)
            WorkResult.Failure(e, e.message)
        }
    }
}